package com.quanyan.place.web;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.place.component.MerchantClientPayType;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.TbBizPlaceOrder;
import com.quanyan.place.entity.apireq.ReqPlaceTicket;
import com.quanyan.place.entity.apireq.ReqQRCode;
import com.quanyan.place.entity.apireq.ReqTicketPay;
import com.quanyan.place.entity.apiresp.RespPlaceTicketStatistics;
import com.quanyan.place.entity.vo.PlaceFinanceAuditVo;
import com.quanyan.place.entity.vo.PlacePrintVo;
import com.quanyan.place.entity.vo.PlaceScanOrderPayVo;
import com.quanyan.place.mapper.PosUnionPayMapper;
import com.quanyan.place.service.ApiPlaceTicketService;
import com.quanyan.place.service.FinanceService;
import com.quanyan.place.service.PlaceOrderService;
import com.quanyan.place.service.PlaceOrderUtilService;
import com.quanyan.place.service.PlaceTicketService;

/**
 * Created by youxiaojia on 2016/9/22.
 */
@RestController
@RequestMapping("/admin/api/place/ticket")
public class PlaceTicketController {
	
	private final static Logger logger = LoggerFactory.getLogger(PlaceTicketController.class);

	@Autowired
	private PlaceTicketService placeTicketService;

	@Autowired
	PlaceOrderService placeOrderService;
	
	 @Autowired
	 PosUnionPayMapper posUnionPayMapper;

    @Autowired
    ApiPlaceTicketService apiPlaceTicketService;

	@Autowired
	PlaceOrderUtilService placeOrderUtilService;

	@Autowired
	FinanceService financeService;
	/**
	 * 添加门票销售
	 * 
	 * @param reqPlaceTicket
	 * @return
	 */
	@RequestMapping(value = "/addPlaceTicket", method = RequestMethod.POST)
	@ResponseBody
	public APIResponse<?> addPlaceTicket(@RequestBody @Valid ReqPlaceTicket reqPlaceTicket,
			BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		APIResponse apiResponse = placeTicketService.insertPlaceTicket(reqPlaceTicket);
		return apiResponse;
	}

	/**
	 * 门票销售列表
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/queryPlaceTicketList", method = RequestMethod.POST)
	@ResponseBody
	public APIResponse<?> queryPlaceTicketList(@RequestBody @Valid Map<String, Object> map,
			BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		Integer placeId = MapUtils.getInteger(map, "placeId");
		Integer categoryId = MapUtils.getInteger(map, "categoryId");
		if (StringUtils.isEmpty(placeId)) {
			return APIResponse.returnFail("placeId为空！");
		}
		APIResponse apiResponse = placeTicketService.queryPlaceTicketList(placeId, categoryId);
		return apiResponse;
	}

	/**
	 * 取消门票销售
	 * 
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/cancelPlaceTicketSale", method = RequestMethod.POST)
	@ResponseBody
	public APIResponse<?> cancelPlaceTicketSale(@RequestBody @Valid Map<String, Object> map,
			BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		Integer ticketId = MapUtils.getInteger(map, "ticketId");
		Integer uid = MapUtils.getInteger(map, "uid");
		if (StringUtils.isEmpty(ticketId)) {
			return APIResponse.returnFail("ticketId为空！");
		}
		if (StringUtils.isEmpty(uid)) {
			return APIResponse.returnFail("uid为空！");
		}
		APIResponse apiResponse = placeTicketService.cancelPlaceTicketSale(ticketId, uid);
		return apiResponse;
	}

	/**
	 * 根据门票id查询门票详情
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/getPlaceTicketSaleDetailById", method = RequestMethod.POST)
	@ResponseBody
	public APIResponse<?> getPlaceTicketSaleDetailById(@RequestBody @Valid Map<String, Object> map,
			BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		Integer ticketId = MapUtils.getInteger(map, "ticketId");
		if (StringUtils.isEmpty(ticketId)) {
			return APIResponse.returnFail("ticketId为空！");
		}
		APIResponse apiResponse = placeTicketService.getPlaceTicketSaleDetailById(ticketId);
		return apiResponse;
	}

	/**
	 * 编辑门票
	 * 
	 * @param reqPlaceTicket
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/editPlaceTicketSale", method = RequestMethod.POST)
	@ResponseBody
	public APIResponse<?> editPlaceTicketSale(@RequestBody @Valid ReqPlaceTicket reqPlaceTicket,
			BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		APIResponse apiResponse = placeTicketService.editPlaceTicketSale(reqPlaceTicket);
		return apiResponse;
	}

	/**
	 * 门票查询会员卡根据手机号
	 */
	@RequestMapping(value = "/queryNumCardList", method = RequestMethod.POST)
	@ResponseBody
	public APIResponse<?> queryNumCardList(@RequestBody @Valid Map<String, Object> map, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		Integer placeId = MapUtils.getInteger(map, "placeId");
		String phone = MapUtils.getString(map, "phone");
		APIResponse apiResponse = placeTicketService.queryNumCardList(placeId, phone);
		return apiResponse;
	}
	
	/**
	 * 门票查询会员卡根据手机号，姓名模糊查询
	 */
	@RequestMapping(value = "/querymemberNumCardList", method = RequestMethod.POST)
	@ResponseBody
	public APIResponse<?> querymemberNumCardList(@RequestBody @Valid Map<String, Object> map, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		try {
			Integer placeId = MapUtils.getInteger(map, "placeId");
			String key = MapUtils.getString(map, "key");
			
			Assert.notNull(placeId, "场馆ID不能为空");
			Assert.hasText(key, "手机号或姓名不能为空");
			
			return  placeTicketService.querymemberNumCardList(placeId, key);
		}catch(IllegalArgumentException ae){
			logger.warn("传入参数异常", ae);
			return  APIResponse.returnFail(ae.getMessage());
		}catch (Exception e) {
			logger.error("查询门票会员卡失败", e);
			return  APIResponse.returnFail(e.getMessage());
		}
	}

	/**
	 * 购买门票
	 * 
	 * @param reqTicketPay
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/buyTicket", method = RequestMethod.POST)
	@ResponseBody
	public APIResponse<?> ticketPay(@RequestBody @Valid ReqTicketPay reqTicketPay, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		
		APIResponse apiResponse = null;
		boolean isScanPayFlag = false;
		if(MerchantClientPayType.getMatchScanPayType().containsKey(reqTicketPay.getAdminPayType().toString())){
			isScanPayFlag = true;
		}

		boolean isCompanyFlag = false;//对公转账
		if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(reqTicketPay.getAdminPayType().toString())){//对公转账支付方式匹配
			isCompanyFlag = true;
		}
		try {
			if (isScanPayFlag) {
				APIResponse orderResponse = placeTicketService.ticketPayForScanPay(reqTicketPay);
				if (orderResponse.isRet() && orderResponse.getData() != null) {
					TbBizPlaceOrder tbBizPlaceOrder = (TbBizPlaceOrder) orderResponse.getData();
					PlaceScanOrderPayVo placeScanOrderPayVo = new PlaceScanOrderPayVo();
					placeScanOrderPayVo.setReceivedAmount(new BigDecimal(reqTicketPay.getReceivedAmount()));
					placeScanOrderPayVo.setAdminPayType(reqTicketPay.getAdminPayType().toString());
					placeScanOrderPayVo.setScanCode(reqTicketPay.getScanCode());
					placeScanOrderPayVo.setTbBizPlaceOrder(tbBizPlaceOrder);
					placeScanOrderPayVo.setTbBizPlacePrivateOrder(null);
					placeScanOrderPayVo.setReqTicketPay(reqTicketPay);
					apiResponse = placeOrderService.scanOrderPay(placeScanOrderPayVo);
				} else {
					return APIResponse.returnFail("扫码购买门票生成订单失败");
				}
			} else if (isCompanyFlag){
				APIResponse orderResponse = placeTicketService.ticketPayForScanPay(reqTicketPay);
				if (orderResponse.isRet() && orderResponse.getData() != null) {
					TbBizPlaceOrder tbBizPlaceOrder = (TbBizPlaceOrder)orderResponse.getData();

					//插入审核记录
					PlaceFinanceAuditVo placeFinanceAuditVo = placeOrderUtilService.tbBizPlaceOrder2PlaceFinanceAuditVo(tbBizPlaceOrder);
					if (!StringUtils.isEmpty(placeFinanceAuditVo)){
						financeService.createAuditRecord(placeFinanceAuditVo);
					}

					//打印小票
					PlacePrintVo placePrintVo = new PlacePrintVo();
					placePrintVo.setIsMember(PlaceConstants.NO);
					placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_TICKET);
					placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
					return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
				} else {
					return APIResponse.returnFail("对公转账生成订单失败");
				}
			} else {
				apiResponse = placeTicketService.ticketPay(reqTicketPay);
			}
			return apiResponse;
		} catch (Exception e) {
			e.printStackTrace();
			return APIResponse.returnFail(e.getMessage());
		}
	}

	/**
	 * 门票销售明细
	 * 
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/ticketSaleDetail", method = RequestMethod.POST)
	@ResponseBody
	public APIResponse<PageObj<List<RespPlaceTicketStatistics>>> ticketSaleDetail(
			@RequestBody @Valid Map<String, Object> map, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		Integer placeId = MapUtils.getInteger(map, "placeId");
		String startDate = MapUtils.getString(map, "startDate");
		String endDate = MapUtils.getString(map, "endDate");
		Integer pageNum = MapUtils.getInteger(map, "pageNum");
		Integer pageSize = MapUtils.getInteger(map, "pageSize");
		if (StringUtils.isEmpty(MapUtils.getLong(map, "startDate"))
				|| StringUtils.isEmpty(MapUtils.getLong(map, "endDate"))) {
			return APIResponse.returnSuccess();
		}
		Date startDate1 = DateUtils.dateStrToDate(startDate);
		Date endDate1 = DateUtils.dateStrToDate(endDate);
		APIResponse apiResponse = placeTicketService.ticketSaleDetail(placeId, startDate1, endDate1, pageNum, pageSize);
		return apiResponse;
	}

	/**
	 * 门票销售统计导出
	 * 
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/ticketSaleDetailExport", method = RequestMethod.POST)
	@ResponseBody
	public APIResponse<PageObj<List<RespPlaceTicketStatistics>>> ticketSaleDetailExport(
			@RequestBody @Valid Map<String, Object> map, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		Integer placeId = MapUtils.getInteger(map, "placeId");
		String startDate = MapUtils.getString(map, "startDate");
		String endDate = MapUtils.getString(map, "endDate");
		if (StringUtils.isEmpty(MapUtils.getLong(map, "startDate"))
				|| StringUtils.isEmpty(MapUtils.getLong(map, "endDate"))) {
			return APIResponse.returnSuccess();
		}
		Date startDate1 = DateUtils.dateStrToDate(startDate);
		Date endDate1 = DateUtils.dateStrToDate(endDate);
		APIResponse apiResponse = placeTicketService.ticketSaleDetailExport(placeId, startDate1, endDate1);
		return apiResponse;
	}

    /**
     * 微信生成二维码
     * @param reqQRCode
     * @param response
     */
    @RequestMapping(value="/ticketQRCodeCreate", method = RequestMethod.POST)
    public APIResponse<?> ticketQRCodeCreate(@RequestBody @Valid ReqQRCode reqQRCode,HttpServletResponse response,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID.toString());
        }
        response.setContentType("image/jpeg");
        String result = apiPlaceTicketService.ticketQRCodeCreate(reqQRCode);
        return APIResponse.returnSuccess(result);

    }

	/**
	 * 门票销售明细
	 * @return
     */
	@RequestMapping(value="/getTicketDetail",method = RequestMethod.POST)
	public APIResponse<?> getTicketDetail(@RequestBody @Valid Map<String,Object> map,BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			return  APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		return placeTicketService.getTicketDetail(map);
	}

	/**
	 * 门票销售明细导出
	 *
	 * @param map
	 * @param bindingResult
     * @return
     */
	@RequestMapping(value="/getTicketDetailExport",method = RequestMethod.POST)
	public APIResponse<?> getTicketDetailExport(@RequestBody @Valid Map<String,Object> map,BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			return  APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		return placeTicketService.getTicketDetailExport(map);
	}

	/**
	 * 门票销售统计  --按门票编号
	 *
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value="/getTicketStatisticsByTicketCode",method = RequestMethod.POST)
	public APIResponse<?> getTicketStatisticsByTicketCode(@RequestBody @Valid Map<String,Object> map,BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			return  APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		return placeTicketService.getTicketStatisticsByTicketCode(map);
	}

	/**
	 * 门票销售统计   --门票编号(导出)
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/getTicketStatisticsByTicketCodeExport",method = RequestMethod.POST)
	public APIResponse<?> getTicketStatisticsByTicketCodeExport(@RequestBody @Valid Map<String, Object> map,
																 BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		map.put("pageNum",null);
		map.put("pageSize",null);
		return placeTicketService.getTicketStatisticsByTicketCodeExport(map);
	}

	/**
	 * 门票销售统计   --销售渠道
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/getTicketStatisticsByOrderChannel",method = RequestMethod.POST)
	public APIResponse<?> getTicketStatisticsByOrderChannel(@RequestBody @Valid Map<String, Object> map,
															  BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		return placeTicketService.getTicketStatisticsByOrderChannel(map);
	}

	/**
	 * 门票销售统计   --销售渠道(导出)
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/getTicketStatisticsByOrderChannelExport",method = RequestMethod.POST)
	public APIResponse<?> getTicketStatisticsByOrderChannelExport(@RequestBody @Valid Map<String, Object> map,
																	BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		return placeTicketService.getTicketStatisticsByOrderChannel(map);
	}

	/**
	 * 门票销售统计   --运动项目
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/getTicketStatisticsByCategory",method = RequestMethod.POST)
	public APIResponse<?> getTicketStatisticsByCategory(@RequestBody @Valid Map<String, Object> map,
														  BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		return placeTicketService.getTicketStatisticsByCategory(map);
	}

	/**
	 * 门票销售统计   --运动项目(导出)
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/getTicketStatisticsByCategoryExport",method = RequestMethod.POST)
	public APIResponse<?> getTicketStatisticsByCategoryExport(@RequestBody @Valid Map<String, Object> map,
																BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		return placeTicketService.getTicketStatisticsByCategory(map);
	}

	/**
	 * 门票销售统计   --散客会员
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/getTicketStatisticsByMember",method = RequestMethod.POST)
	public APIResponse<?> getTicketStatisticsByMember(@RequestBody @Valid Map<String, Object> map,
														BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		return placeTicketService.getTicketStatisticsByMember(map);
	}

	/**
	 * 门票销售统计   --散客会员(导出)
	 * @param map
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping(value = "/getTicketStatisticsByMemberExport",method = RequestMethod.POST)
	public APIResponse<?> getTicketStatisticsByMemberExport(@RequestBody @Valid Map<String, Object> map,
															  BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
		}
		return placeTicketService.getTicketStatisticsByMember(map);
	}
}
